import { useState, useEffect } from 'react'
import { useWeb3Contract, useMoralis } from 'react-moralis'
import NFTSHOPAbi from '../constant/NFTSHOP.json'
import nftAbi from '../constant/BasicNFT.json'
import Image from 'next/image'
import { Card, useNotification } from '@web3uikit/core'
import { ethers } from 'ethers'
import UpdateListingModal from './UpdateListingModal'
import React from 'react'

const truncateStr = (fullStr, strLen) => {
  if (fullStr.length <= strLen) return fullStr

  const separator = '...'
  const seperatorLength = separator.length
  const charsToShow = strLen - seperatorLength
  const frontChars = Math.ceil(charsToShow / 2)
  const backChars = Math.floor(charsToShow / 2)
  return fullStr.substring(0, frontChars) + separator + fullStr.substring(fullStr.length - backChars)
}

export default function NFTBox({ price, nftAddress, tokenId, NFTShopAddress, seller }) {
  console.log(nftAddress, tokenId, NFTShopAddress)
  const { isWeb3Enabled, account } = useMoralis()
  const [imageURI, setImageURI] = useState('')
  const [tokenName, setTokenName] = useState('')
  const [tokenDescription, setTokenDescription] = useState('')
  const [showModal, setShowModal] = useState(false)
  const hideModal = () => setShowModal(false)
  const dispatch = useNotification()

  const { runContractFunction: getTokenURI } = useWeb3Contract({
    abi: nftAbi,
    contractAddress: nftAddress,
    functionName: 'tokenURI',
    params: {
      tokenId: tokenId
    }
  })

  const { runContractFunction: buyItem } = useWeb3Contract({
    abi: NFTSHOPAbi,
    contractAddress: NFTShopAddress,
    functionName: ' BuyNft',
    msgValue: price,
    params: {
      nftAddress: nftAddress,
      tokenId: tokenId
    }
  })

  async function updateUI() {
    let tokenURI = await getTokenURI()
    console.log(`The TokenURI is ${tokenURI}`)
    if (tokenURI === undefined) {
      tokenURI = 'ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json'
    }
    // We are going to cheat a little here...
    if (tokenURI !== undefined) {
      // IPFS Gateway: A server that will return IPFS files from a "normal" URL.
      // @ts-ignore
      const requestURL = tokenURI.replace('ipfs://', 'https://ipfs.io/ipfs/')
      const tokenURIResponse = await (await fetch(requestURL)).json()
      const imageURI = tokenURIResponse.image
      const imageURIURL = imageURI.replace('ipfs://', 'https://ipfs.io/ipfs/')
      setImageURI(imageURIURL)
      setTokenName(tokenURIResponse.name)
      setTokenDescription(tokenURIResponse.description)
      // We could render the Image on our sever, and just call our sever.
      // For testnets & mainnet -> use moralis server hooks
      // Have the world adopt IPFS
      // Build our own IPFS gateway
    }
    // get the tokenURI
    // using the image tag from the tokenURI, get the image
  }

  useEffect(() => {
    if (isWeb3Enabled) {
      updateUI()
    }
  }, [isWeb3Enabled])

  const isOwnedByUser = seller === account || seller === undefined
  const formattedSellerAddress = isOwnedByUser ? 'you' : truncateStr(seller || '', 15)

  const handleCardClick = () => {
    isOwnedByUser
      ? setShowModal(true)
      : buyItem({
          onError: error => console.log(error),
          onSuccess: handleBuyItemSuccess
        })
  }

  const handleBuyItemSuccess = async tx => {
    await tx.wait(1)
    dispatch({
      type: 'success',
      message: 'Item bought!',
      title: 'Item Bought',
      position: 'topR'
    })
  }

  return (
    <div>
      <div>
        {imageURI ? (
          <div>
            <UpdateListingModal
              isVisible={showModal}
              tokenId={tokenId}
              NFTShopAddress={NFTShopAddress}
              nftAddress={nftAddress}
              onClose={hideModal}
            />
            <Card title={tokenName} description={tokenDescription} onClick={handleCardClick}>
              <div className="p-2">
                <div className="flex flex-col items-end gap-2">
                  <div>#{tokenId}</div>
                  <div className="italic text-sm">Owned by {formattedSellerAddress}</div>
                  <Image loader={() => imageURI} src={imageURI} height="200" width="200" alt={''} />
                  <div className="font-bold">{ethers.utils.formatUnits(price, 'ether')} ETH</div>
                </div>
              </div>
            </Card>
          </div>
        ) : (
          <div>Loading...</div>
        )}
      </div>
    </div>
  )
}
